import axios from 'axios'

export interface OilPriceData {
  province: string
  oilType: string
  price: number
  change: number
  changePercent: number
  lastUpdated: string
}

export interface OilPriceResponse {
  success: boolean
  data: OilPriceData[]
  message: string
  timestamp: string
}

class OilPriceService {
  // mxnzp.com免费API配置
  private readonly BASE_URL = 'https://www.mxnzp.com/api/oil/search'
  private readonly APP_ID = import.meta.env.VITE_MXNZP_APP_ID || 'lkidl1qrmodojuip'
  private readonly APP_SECRET = import.meta.env.VITE_MXNZP_APP_SECRET || 'LlGt9UGGI6xQY9EO3BCylql3co3X7F3t'

  /**
   * 获取今日油价列表
   * @param province 省份，可选参数
   * @returns Promise<OilPriceResponse>
   */
  async getTodayOilPrices(province?: string): Promise<OilPriceResponse> {
    try {
      const provincesToFetch = province ? [province] : this.getSupportedProvinces();
      const oilPriceData: OilPriceData[] = [];

      for (const prov of provincesToFetch) {
        try {
          const response = await axios.get(this.BASE_URL, {
            params: {
              province: prov,
              app_id: this.APP_ID,
              app_secret: this.APP_SECRET
            }
          });

          if (response.data.code === 1 && response.data.data) {
            const data = response.data.data;
            
            // 转换API数据格式为OilPriceData
            const oilTypes = [
              { type: '92号汽油', price: parseFloat(data.t92) || 0 },
              { type: '95号汽油', price: parseFloat(data.t95) || 0 },
              { type: '98号汽油', price: parseFloat(data.t98) || 0 },
              { type: '0号柴油', price: parseFloat(data.t0) || 0 },
              { type: '89号汽油', price: parseFloat(data.t89) || 0 }
            ];

            oilTypes.forEach(oilType => {
              if (oilType.price > 0) {
                oilPriceData.push({
                  province: prov,
                  oilType: oilType.type,
                  price: oilType.price,
                  change: 0, // mxnzp.com API不提供涨跌数据，设为0
                  changePercent: 0, // mxnzp.com API不提供涨跌百分比，设为0
                  lastUpdated: new Date().toISOString()
                });
              }
            });
          }
        } catch (error) {
          console.error(`获取${prov}油价数据失败:`, error);
        }
      }

      return {
        success: true,
        data: oilPriceData,
        message: '获取成功',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      console.error('获取油价数据失败:', error);
      return {
        success: false,
        data: [],
        message: '获取油价数据失败，请稍后重试',
        timestamp: new Date().toISOString()
      };
    }
  }

  /**
   * 获取支持的省份列表
   * @returns string[]
   */
  getSupportedProvinces(): string[] {
    return [
      '北京', '上海', '广东', '江苏', '浙江', '山东', '河南', 
      '河北', '四川', '湖北', '湖南', '福建', '安徽', '辽宁',
      '陕西', '江西', '重庆', '云南', '贵州', '广西', '山西',
      '内蒙古', '吉林', '黑龙江', '天津', '甘肃', '宁夏', '新疆',
      '海南', '青海', '西藏'
    ]
  }

  /**
   * 获取支持的油品类型
   * @returns string[]
   */
  getSupportedOilTypes(): string[] {
    return [
      '92号汽油', '95号汽油', '98号汽油', '0号柴油', '-10号柴油'
    ]
  }

  /**
   * 获取模拟油价数据
   * @param province 省份
   * @returns OilPriceResponse
   */
  private getMockOilPrices(province?: string): OilPriceResponse {
    const mockData: OilPriceData[] = []
    const provinces = province ? [province] : this.getSupportedProvinces().slice(0, 5)
    const oilTypes = this.getSupportedOilTypes()

    provinces.forEach(prov => {
      oilTypes.forEach(oilType => {
        const basePrice = this.getBasePrice(oilType)
        const change = (Math.random() - 0.5) * 0.2
        
        mockData.push({
          province: prov,
          oilType: oilType,
          price: Number((basePrice + change).toFixed(2)),
          change: Number(change.toFixed(2)),
          changePercent: Number(((change / basePrice) * 100).toFixed(2)),
          lastUpdated: new Date().toISOString()
        })
      })
    })

    return {
      success: true,
      data: mockData,
      message: '获取成功',
      timestamp: new Date().toISOString()
    }
  }

  /**
   * 获取基础价格
   * @param oilType 油品类型
   * @returns number
   */
  private getBasePrice(oilType: string): number {
    const basePrices: Record<string, number> = {
      '92号汽油': 7.5,
      '95号汽油': 8.0,
      '98号汽油': 8.5,
      '0号柴油': 7.2,
      '-10号柴油': 7.6
    }
    return basePrices[oilType] || 7.5
  }
}

export default new OilPriceService()